package 栈算法;

import org.junit.Test;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

public class longestValidParentheses32 {
    /**
     * 最长连续有效括号
     *
     * @param s
     * @return
     */
    public int longestValidParentheses(String s) {
        if (s.length() == 0) {
            return 0;
        }
        int maxans = 0;
        Deque<Integer> stack = new LinkedList<Integer>();// 存储的是下标的元素
        stack.push(-1);
        // 遍历字符
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else {
                stack.pop();
                // 判断时候为空
                if (stack.isEmpty()) {
                    stack.push(i);
                } else {
                    maxans = Math.max(maxans, i - stack.peek());
                }
            }
        }
        return maxans;
    }

    /**
     * 利用栈的思想来实现
     *
     * @param s
     * @return
     */
    public int longestValidParentheses2(String s) {
        if (s.length() == 0) {
            return 0;
        }
        int maxlen = 0;
        Stack<Integer> stack = new Stack<>();
        stack.add(-1);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.add(i);
            } else {
                stack.pop();
                if (stack.isEmpty()) {
                    stack.add(i);
                } else {
                    maxlen = Math.max(maxlen, i - stack.peek());
                }
            }
        }
        return maxlen;
    }

    @Test
    public void test() {
        int i = longestValidParentheses("()(()");
        System.out.println(i);
    }
}
